package helper

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Code      int         `json:"code"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"msg"`
	Success   bool        `json:"success"`
	Err       error       `json:"err,omitempty"`
	TimeStamp int64       `json:"timestamp,omitempty"` // 服务器时间戳
}

const (
	FAIL = 500
)

type Page struct {
	Total       int64       `json:"total,omitempty"`
	CurrentPage int         `json:"page,omitempty"`
	PageSize    int         `json:"size,omitempty"`
	List        interface{} `json:"list,omitempty"`
}

func Error(err error) Response {
	return Response{
		Msg:  err.Error(),
		Data: map[string]interface{}{},
		Code: FAIL,
		Err:  err,
	}
}

// JSON 返回执行结果
func JSON(ctx *gin.Context, resp Response) {
	ctx.Set("result", resp)
	resp.Success = true
	ctx.JSON(http.StatusOK, resp)
}

// JsonError 返回错误码
func JsonError(ctx *gin.Context, httpCode int, resp Response) {
	if resp.Err != nil {
		resp.Msg = resp.Err.Error()
	}
	ctx.Set("result", resp)
	resp.Success = false
	// 响应客户端
	ctx.JSON(httpCode, resp)
}
